package com.easyexcell.easyexcellexample.utils.esayexcell;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.NonNull;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author c.c
 * @Since 2023/4/24
 * @Time 18:29
 * @Description
 */

public class EasyExcelUtil {

  /**
   * 数据导出
   *
   * @param sourceList       导出数据列表
   * @param title            表头 （可以为空）
   * @param templateFileName 模板文件名字
   * @param inputStream      输入流
   * @param response         响应
   * @return
   * @author C.c
   * @since 2023-05-22 16:07
   **/
  public static void downLoadExcel(@NonNull List<?> sourceList, Object title, @NonNull String templateFileName, @NonNull InputStream inputStream,@NonNull HttpServletResponse response) {
    try {
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(templateFileName, "UTF-8") + ".xlsx");

      try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build()) {
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(sourceList, writeSheet);
        if (title != null) {
          excelWriter.fill(title, writeSheet);
        }
        excelWriter.close();
        excelWriter.finish();
      }

    } catch (IOException e) {
      throw new RuntimeException(e.getMessage());
    }
  }

  /**
   * 注:在添加自己的导入文件后，需要在当前目录下的listen目录下实现新的监听。
   *
   * @param
   * @return
   * @author C.c
   * @since 2023-05-22 10:39
   **/

  public static boolean importExcell(MultipartFile file, Class<?> targetClass, ReadListener<?> readListener, int contentIndex) {
    try {
      EasyExcel.read(file.getInputStream(), targetClass, readListener).headRowNumber(contentIndex).sheet().doRead();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return true;
  }

}
